package gift.justflower.ecp.controller;

import gift.justflower.ecp.bean.Goods;
import gift.justflower.ecp.bean.Sell;
import gift.justflower.ecp.bean.User;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import java.util.List;
import java.util.Date;

/**
 * 销售相关方法
 * author：AB
 * time：2018年7月17日 23:05:16
 */
@IocBean
public class SellController {
    @Inject
    private Dao dao;

    @At("/sell/del")
    @RequiresUser
    public NutMap del(@Param("id") String id) {
        dao.delete(Sell.class, id);
        return new NutMap("ok", true);
    }

    @At("/sell")
    @RequiresUser
    @Ok("beetl:/html/sell.html")
    public void sell(@Param("..") Pager pager) {
        if (null == pager) {
            pager = new Pager();
            pager.setPageNumber(1);
            pager.setPageSize(20);
        }
        User user = (User) Mvcs.getHttpSession().getAttribute("user");
        pager.setRecordCount(dao.count(Sell.class, Cnd.where("userId", "=", user.getId())));
        List<Sell> sellList = dao.query(Sell.class, Cnd.where("userId", "=", user.getId()).desc("createTime"), pager);
        dao.fetchLinks(sellList, null);
        Mvcs.getReq().setAttribute("queryResult", new QueryResult(sellList, pager));
        Mvcs.getReq().setAttribute("goodsList", dao.query(Goods.class, Cnd.where("userId", "=", user.getId())));
    }

    @At("/sell/add")
    @Ok(">>:/sell")
    @RequiresUser
    public void add(@Param("..") Sell sell) {
        User user = (User) Mvcs.getHttpSession().getAttribute("user");
        sell.setUserId(user.getId());
        if (Strings.isEmpty(sell.getId())) {
            sell.setCreateTime(new Date());
            dao.insert(sell);
        } else {
            dao.updateIgnoreNull(sell);
        }

        Goods goods = dao.fetch(Goods.class, Cnd.where("id", "=", sell.getGoodsId()));
        goods.setStock(goods.getStock() - sell.getCount());
        dao.updateIgnoreNull(goods);
    }
}